package tom.oauth2.service;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import tom.oauth2.model.SysUserAuthentication;

/**
 * @author ZHUFEIFEI
 */
@Service
public class MyEventService {

    @Autowired
    private ApplicationContext applicationContext;

    public void createUser() {
        SysUserAuthentication user = new SysUserAuthentication();
        //发布事件
        this.applicationContext.publishEvent(new UserRegEvent(this, user));
    }
}

/**
 * 自定义事件
 */
class UserRegEvent extends ApplicationEvent {

    @Getter
    private SysUserAuthentication user;

    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public UserRegEvent(Object source, SysUserAuthentication user) {
        super(source);
        this.user = user;
    }
}

/**
 * 定义事件监听处理器
 */
@Slf4j
@Component
class UserRegEventListener {

    /**
     * 注册监听1, 如果event是泛型可以将listener继承SmartApplicationListener
     * Order注解决定监听器的执行顺序(去掉Async注解查看效果)
     * @param event
     */
    @Order(2)
    @Async
    @EventListener
    public void persistDB(UserRegEvent event) {
        log.info("db event source : {} data : {}", event.getSource(), event.getUser());
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
        }
    }

    /**
     * 注册监听2
     * @param event
     */
    @Order(1)
    @Async
    @EventListener
    public void sendEmail(UserRegEvent event) {
        log.info("email event source : {} data : {}", event.getSource(), event.getUser());
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
        }
    }
}